package cn.javass.dp.prototype.demo1;

//复制对象 跟原本对象不是一个对象，但是对象内的引用指向同一个地址
public class Stu implements Cloneable {
    String name;
    Integer age;
    Teacher teacher;

    public Stu() {
        System.out.println("测试clone方法是否调用构造方法");
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public Teacher getTeacher() {
        return teacher;
    }

    public void setTeacher(Teacher teacher) {
        this.teacher = teacher;
    }

    @Override
    public String toString() {
        return "Stu{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", teacher=" + teacher +
                '}';
    }
    @Override
    protected Object clone() throws CloneNotSupportedException {
        Stu newstudent = (Stu) super.clone();
        newstudent.teacher = (Teacher) teacher.clone();  //深拷贝
        return newstudent;
    }

    public static void main(String [] args){
        Teacher t1 = new Teacher();
        t1.setAge(32);
        t1.setName("wang Teacher");
        Stu s1 = new Stu();
        s1.setName("xiao ming");
        s1.setAge(22);
        s1.setTeacher(t1);
        System.out.println("复制前的学生1："+s1);
        try {
            Stu s2 = (Stu) s1.clone();
            s2.setName("da ming");
            s2.setAge(24);
            Teacher t2 = s2.getTeacher();
            t2.setName("zhao Teacher");
            t2.setAge(34);
            s2.setTeacher(t2);
            System.out.println("复制后的学生1："+s1);
            System.out.println("复制后的学生2："+s2);
            System.out.println("teacher的地址"+s1.getTeacher().hashCode());
            System.out.println("teacher的地址"+s2.getTeacher().hashCode());

        } catch (CloneNotSupportedException e) {
        }

    }
}